﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
* 项目名称 ：APP.Member.Service
* 项目描述 ：
* 类 名 称 ：CoreService
* 类 描 述 ：
* 所在的域 ：DESKTOP-07DQ4D0
* 命名空间 ：APP.Member.Service
* 机器名称 ：DESKTOP-07DQ4D0 
* CLR 版本 ：4.0.30319.42000
* 作    者 ：Me.笨先生 (66623978)
* 创建时间 ：2018/2/6 11:38:58
* 更新时间 ：2018/2/6 11:38:58
* 版 本 号 ：v1.0.0.0
*******************************************************************
* Copyright @ admin 2018. All rights reserved.
*******************************************************************
//----------------------------------------------------------------*/
#endregion

using System;

using APP.Repository;
using APP.Repository.SqlServer;

using APP.CommonLib.Log;
using APP.CommonLib.Cache;
using APP.CommonLib.Utils;
using APP.CommonLib.Config;
using APP.CommonLib.Extension;

using APP.Member.Entity;
using APP.Account.Entity;

namespace APP.Member.Service
{
    public class CoreService
    {
        #region 单例实例 Instance
        readonly static MsSqlContext smsContext = new MsSqlContext(ConfigManager.GetWebConn("sms", ""));
        readonly static MsSqlContext basicContext = new MsSqlContext(ConfigManager.GetWebConn("basic", ""));

        public static CoreService Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (Lockobj)
                    {
                        if (_instance == null)
                            _instance = new CoreService();
                    }
                }
                return _instance;
            }
        }

        private static CoreService _instance;

        private static readonly object Lockobj = new object();

        private CoreService()
        {

        }
        #endregion



        /// <summary>
        /// 获取短信验证码
        /// </summary>
        /// <param name="para"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public OperatorStatus GetVcode(GetVCodeParameter para, out string errorMsg)
        {
            try
            {
                IQuery<MemberEntity> basicRepository = basicContext.Query<MemberEntity>();
                IQuery<SmsMessageEntity> smsRepository = smsContext.Query<SmsMessageEntity>();

                //如果号码中有星号，那么通过memberid取出phone
                if (para.Phone.IndexOf("*") > 0)
                {
                    var info = basicRepository.Where(m => m.Id == para.MemberId).FirstOrDefault();
                    if (info == null)
                    {
                        errorMsg = "token无效";
                        return OperatorStatus.Error;
                    }
                    para.Phone = info.Phone;
                }

                var memberInfo = basicRepository.Where(m => m.Phone == para.Phone).FirstOrDefault();

                switch (para.Type)
                {
                    case SmsType.Regist:
                        if (memberInfo != null)
                        {
                            errorMsg = "此手机号码已被注册";
                            return OperatorStatus.Error;
                        }
                        break;
                    case SmsType.FindLogPwd:
                    case SmsType.FindTradePwd:
                        if (memberInfo == null)
                        {
                            errorMsg = "此手机号码还未注册";
                            return OperatorStatus.Error;
                        }
                        break;
                    default:
                        if (memberInfo == null)
                        {
                            errorMsg = "此手机号码还未注册";
                            return OperatorStatus.Error;
                        }
                        break;
                }

                int pSendCnt = smsRepository.Where(s => s.Phone == para.Phone && Sql.DiffDays(s.SendTime, DateTime.Now) == 0).Select(a => Sql.Count()).First();
                if (pSendCnt > 10)
                {
                    errorMsg = "今日短信次数已用完";
                    return OperatorStatus.Error;
                }
                if (!string.IsNullOrEmpty(CacheManager.GetRedisCache(MemberCacheString.VCodeCacheSpace, "VCodeSendCnt" + para.Phone)))
                {
                    errorMsg = "1分钟内只可获取一次";
                    return OperatorStatus.Error;
                }

                //是否测试环境
                bool isTestEnv = ConfigManager.GetWebConfig("IsTestEnv", 0) == 1 ? true : false;

                var code = CacheManager.GetRedisCache(MemberCacheString.VCodeCacheSpace, para.Phone.GetVCodeByPhone());
                if (string.IsNullOrEmpty(code))
                {
                    if (isTestEnv)
                    {
                        code = "0000";
                    }
                    else
                    {
                        code = RandomHelper.GenerateCheckCodeNum(4);
                    }
                }

                var p = para.Phone.ToLong();
                var t = para.Type.ToInt();

                CacheManager.PutRedisCache(MemberCacheString.VCodeCacheSpace, para.Phone.GetVCodeByPhone(), code, 60 * 2);
                //发送次数插入Redis
                CacheManager.PutRedisCache(MemberCacheString.VCodeCacheSpace, "VCodeSendCnt" + p, p.ToString() + t, 60);

                smsContext.Insert(new SmsMessageEntity { Phone = para.Phone, Msg = "您的验证码是：" + code, SendCount = 0, Status = 0, Sign = 0 });
                basicContext.Insert(new ValidationCodeEntity { TypeId = t, Phone = p, ValidationCode = code, CreateTime = DateTime.Now, LastUpdateTime = DateTime.Now });

                errorMsg = $"短信发送成功,今日剩余{10 - pSendCnt}次";
                return OperatorStatus.Success;
            }
            catch (Exception ex)
            {
                Logger.Error("MemberService.GetVCode", ex);
                errorMsg = "短信发送失败";
                return OperatorStatus.Error;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public OperatorStatus Regist()
        {
            return OperatorStatus.Success;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="para"></param>
        /// <param name="errorMsg"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        public OperatorStatus Login(LoginParameter para, out string errorMsg, out LoginResponse response)
        {
            errorMsg = "";
            response = new LoginResponse();

            var id = para.Phone.ToLong();
            if (id < 1)
            {
                errorMsg = "账号或密码错误";
                return OperatorStatus.Error;
            }

            try
            {
                IQuery<MemberEntity> basicRepository = basicContext.Query<MemberEntity>();
                IQuery<SmsMessageEntity> smsRepository = smsContext.Query<SmsMessageEntity>();

                //如果号码中有星号，那么通过memberid取出phone
                if (para.Phone.IndexOf("*") > 0)
                {
                    //var info = basicRepository.Where(m => m.Id == para.MemberId).FirstOrDefault();
                    //if (info == null)
                    //{
                    //    errorMsg = "token无效";
                    //    return OperatorStatus.Error;
                    //}
                    //para.Phone = info.Phone;
                }

                var memberInfo = basicRepository.Where(m => m.Phone == para.Phone).FirstOrDefault();

                //switch (para.Type)
                //{
                //    case SmsType.Regist:
                //        if (memberInfo != null)
                //        {
                //            errorMsg = "此手机号码已被注册";
                //            return OperatorStatus.Error;
                //        }
                //        break;
                //    case SmsType.FindLogPwd:
                //    case SmsType.FindTradePwd:
                //        if (memberInfo == null)
                //        {
                //            errorMsg = "此手机号码还未注册";
                //            return OperatorStatus.Error;
                //        }
                //        break;
                //    default:
                //        if (memberInfo == null)
                //        {
                //            errorMsg = "此手机号码还未注册";
                //            return OperatorStatus.Error;
                //        }
                //        break;
                //}

                DateTime startTime = DateTime.Now;
                DateTime endTime = DateTime.Now.AddDays(1);

                int pSendCnt = smsRepository.Where(s => s.Phone == para.Phone && Sql.DiffHours(startTime, endTime) < 24).Select(a => Sql.Count()).First();

                errorMsg = "短信发送失败";
                return OperatorStatus.Error;
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
